package zredis

import (
	"errors"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
)

// Init 初始化
func Init(addr, pass string, db int) {

	_addr, _pass, _db = addr, pass, db

	pool = &redis.Pool{
		MaxActive:   10240,
		MaxIdle:     10240,             // Maximum number of idle connections in the pool.
		IdleTimeout: 240 * time.Second, // Close connections after remaining idle for this duration
		Dial:        dial,
		Wait:        true,
	}
}

// GetConn 获取链接
func GetConn() (conn redis.Conn, err error) {
	if pool == nil {
		err = errors.New("zredis pool nil")
		fmt.Println("err", err)
		return nil, err
	}
	conn = pool.Get()
	if conn == nil {
		err = errors.New("zredis conn nil")
		fmt.Println("err", err)
		return nil, err
	}
	return conn, nil
}

// Check 检查
func Check() bool {

	conn, err := GetConn()
	if err != nil {
		return false
	}
	defer autoClose(conn)

	_, err = redis.Int64(conn.Do("GET", "test"))
	if err != nil {
		if err == redis.ErrNil {
			//fmt.Println("redis.ErrNil")
		} else {
			fmt.Println("err", err)
			fmt.Println("redis conn error",
				"_addr", _addr,
				"_pass", _pass,
				"_db", _db)
			return false
		}
	}

	return true
}
